package com.z.redis.command.impl.zset;

import com.z.redis.RedisCore;
import com.z.redis.command.CommandType;
import com.z.redis.command.WriteCommand;
import com.z.redis.datatype.BytesWrapper;
import com.z.redis.datatype.RedisData;
import com.z.redis.datatype.RedisZset;
import com.z.redis.resp.BulkString;
import com.z.redis.resp.Resp;
import com.z.redis.resp.RespInt;
import io.netty.channel.ChannelHandlerContext;

import java.util.ArrayList;
import java.util.List;

/**
 * 向zset添加元素
 */
public class Zadd implements WriteCommand {
    private BytesWrapper key;
    private List<RedisZset.ZsetKey> keys;

    @Override
    public CommandType type(){
        return CommandType.zadd;
    }

    @Override
    public void setContent(Resp[] array){
        key = ((BulkString) array[1]).getContent();
        keys = new ArrayList<>();
        for(int i=2;i+1<array.length;i+=2){
            long score = Long.parseLong(((BulkString) array[i]).getContent().toUTF8String());
            BytesWrapper member = ((BulkString) array[i+1]).getContent();
            keys.add(new RedisZset.ZsetKey(member, score));
        }
    }

    @Override
    public void handle(ChannelHandlerContext ctx, RedisCore redisCore){
        RedisData redisData = redisCore.get(key);
        if(redisData == null){
            RedisZset redisZset = new RedisZset();
            int add = redisZset.add(keys);
            redisCore.put(key, redisZset);
            ctx.writeAndFlush(new RespInt(add));
        }else if(redisData instanceof RedisZset){
            int add = ((RedisZset) redisData).add(keys);
            ctx.writeAndFlush(new RespInt(add));
        }else{
            throw new UnsupportedOperationException("type not support");
        }
    }

    @Override
    public void handle(RedisCore redisCore){
        RedisData redisData = redisCore.get(key);
        if(redisData == null){
            RedisZset redisZset = new RedisZset();
            int add = redisZset.add(keys);
            redisCore.put(key, redisZset);
        }else if(redisData instanceof RedisZset){
            int add = ((RedisZset) redisData).add(keys);
        }else{
            throw new UnsupportedOperationException("type not support");
        }
    }
}
